package com.bj.dz.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.RequestMapping;

import com.bj.dz.entity.User;
import com.bj.dz.service.UserService;
import com.bj.dz.util.Util;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;


    /**
     * 登录
     */
    @RequestMapping("/login.do")
    public boolean login(String userName, String pwd, HttpSession session) {
        User user = userService.findLoginUser(userName, pwd);
        boolean flag = false;
        if (user == null) {
            flag = false;
        } else {
            session.setAttribute("user", user);
            flag = true;
        }
        return flag;
    }


    /**
     * 获取用户列表
     */
    @RequestMapping("/loadUsers.do")
    public List<User> loadUsers() {
        List<User> userList = userService.findUsers();
        return userList;
    }


    /**
     * 保存用户
     */
    @RequestMapping("/saveUser.do")
    public boolean saveUser(User user, HttpServletResponse response) {
        user.setPwd("123456");
        boolean flag = userService.saveUser(user);
        return flag;
    }


    /**
     * 分配角色
     */
    @RequestMapping("/assignRole.do")
    public boolean assignRole(User user) {
        boolean flag = userService.assignRole(user);
        return flag;
    }


    /**
     * 查询角色对应的用户
     */
    @RequestMapping("/findUserByRid.do")
    public List<User> findUserByRid(Integer rid) {
        List<User> userList = userService.findUserByRid(rid);
        return userList;
    }

    /**
     * 重置密码
     */
    @RequestMapping("/resetPwd.do")
    public boolean resetPwd(Integer id) {
        boolean flag = userService.resetPwd(id, Util.default_Pwd);
        return flag;
    }

    /**
     * 推出登录
     */
    @RequestMapping("/logout.do")
    public void logout(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        session.invalidate();
        String path = request.getContextPath();
        try {
            response.sendRedirect(path + "/login.jsp");
        } catch (Exception e) {
            System.out.println("推出登录失败....");
        }
    }

}
